<template>
  <div>
    <!-- 按钮 -->
    <el-button type="primary" plain style="margin: 20px" @click="addTrade">+ 添加</el-button>
    <!-- 表格 -->
    <el-table border :data="list">
      <el-table-column label="序号" width="80px" align="center" type="index"></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌logo">
        <template slot-scope="{row,$index}">
          <img :src="row.logoUrl" alt="" style="width:90px;height:50px">
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{row,$index}">
          <el-button type="warning" @click="updateTradeMark(row)">修改</el-button>
          <el-button type="danger" @click="delTradeMark(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination :current-page="page" :page-sizes="[5, 7, 9]" :page-size="limit"
      layout=" prev, pager, next, jumper,->,sizes,total" :total="total" :pager-count="7"
      @current-change="handleCurrentChangex" @size-change="handleSizeChange"
      style="text-align: center;margin-top: 20px;">
    </el-pagination>

    <el-dialog title="添加品牌" :visible.sync="dialogFormVisible">
      <el-form :model="tmForm" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off" style="width:500px" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌Logo" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/brand-api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip" style="margin-left:80px">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>


export default {
  name: "tradeMark",
  data() {
    return {
      page: 1,
      limit: 5,
      list: [],
      total: 0,
      dialogFormVisible: false,
      tmForm: {
        tmName: "",
        logoUrl: ''
      },
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '请选择图片上传', trigger: 'change' }
        ],
      }
    }
  },
  mounted() {
    // console.log(this.$API);
    this.getMarkList()
  },
  methods: {
    async getMarkList() {
      const { page, limit } = this

      let res = await this.$API.tradeMark.reqTradeMarkList(page, limit)
      if (res.code == 200) {
        this.total = res.data.total
        this.list = res.data.records
      }
    },
    delTradeMark(row) {
      this.$confirm(`你确定删除${row.tmName}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let result = await this.$API.tradeMark.reqDeleteTradeMark(row.id);
        if (result.code == 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
        this.page = this.list.length > 1 ? this.page : this.page - 1
        this.getMarkList()

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    updateTradeMark(row) {

      this.dialogFormVisible = true;
      this.tmForm = Object.assign({}, row)
      // console.log(this.tmForm);
      this.page = this.tmForm.id ? this.page : 1
      this.getMarkList();

    },
    addOrUpdateTradeMark() {
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          this.dialogFormVisible = false;

          //发请求（添加品牌|修改品牌）
          let result = await this.$API.tradeMark.reqAddOrUpdateTradeMark(
            this.tmForm
          );

          if (result.code == 200) {
            //弹出信息:添加品牌成功、修改品牌成功
            this.$message({
              type: "success",
              message: this.tmForm.id ? "修改品牌成功" : "添加品牌成功",
            });
            this.getMarkList();
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      })


      // }

    },
    handleCurrentChangex(pager) {
      this.page = pager
      this.getMarkList()
    },
    handleSizeChange(limit) {
      this.limit = limit
      this.getMarkList()
    },
    addTrade() {//增加
      this.tmForm = { tmName: '', logoUrl: '' }
      this.dialogFormVisible = true
    },
    handleAvatarSuccess(res, file) {

      this.tmForm.logoUrl = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  },
  //添加按钮（添加品牌|修改品牌）

}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>